<template>
	<view>
		<view class="top_title">
			<view class="title">
				<view class="left">
					<u--text text="勘察总流水(不包含新人奖励):" size="16" lineHeight="28" color="#fff" align='center'
						bold></u--text>
				</view>
				<view class="record" @click="gotoRecord">
					<!-- 	<u--text text="抢单记录" size="14" lineHeight="28" color="#fff" ></u--text> -->
					<u-button type="success" size="mini" style="height: 50rpx;">抢单记录</u-button>
				</view>
			</view>
			<view class="new_people">
				<view class="">
					<u--text text="新人勘察奖励" size="12" lineHeight="28" color="#fff"></u--text>
				</view>
				<view class="">
					<u--text text="截止日期" size="12" lineHeight="28" color="#fff"></u--text>
				</view>
			</view>
			<!-- 抢单大厅 -->
			<view class="grabbing_hall">
				<view class="center" @click="gotoGrabbingHall">
					<view class="hall_home">
						<u-icon name="home-fill" size="40" color="#fff"></u-icon>
					</view>
					<u--text text="抢单大厅" size="18" lineHeight="28"></u--text>
				</view>
			</view>
		</view>
		<view class="mid">
			还有<text>{{leftNum||0}}个</text>未完成
		</view>
		<view class="blue">

		</view>
		<view class="bottom">
			<view class="empty" v-if="pageList.length===0">
				<view class="icon">
					<u-icon name="order" size="80" color="#f56e3d"></u-icon>
				</view>
				<u--text text="你今日没有勘察计划，去抢单赚取更多收益吧!" size="14" lineHeight="28" align='center'></u--text>
			</view>
			<view class="page_wrapper" v-else>
				<view v-for="(item, index) in pageList" :key="index">
					<view @click="gotoDetails(item)" class="item">
						<view class="top">
							<view>
								<u--text :text="item.houseName" size="14" lineHeight="28" bold :lines='1'></u--text>
							</view>
							<view class="state">
								<u-tag :text="item.ascription==='1'&&'业主'||item.ascription==='2'&&' 二房东'||'--'"
									size="mini" plain color="#bd3124" shape='circle' style="margin-right: 10rpx;"
									borderColor='#bd3124'></u-tag>
								<u-tag :text="surveyStateObj[item.surveyState]" size="mini" type="info" color="#fff"
									:bgColor="item.surveyState==4?'#eee' :'#f56e3d'" shape='circle'
									borderColor='transparent'></u-tag>
							</view>
						</view>
						<view class="top_mid">
							<view class="map">
								<u-icon size="18" name="map" color="#666"></u-icon>
								<u--text :text="item.locationAddress" size="13" lineHeight="28" color="#666"
									:lines='1'></u--text>
							</view>
							<view>
								<!-- <u-tag text="抢单大厅" size="mini" plain color="#eeaf78"></u-tag> -->
							</view>
						</view>
						<view class="btm">
							<view class="btm_time">
								<u--text text="可拍倒计时:" size="12" lineHeight="28" color='#ee7c2b'></u--text>
								<u-count-down :time="item.timeLeft?item.timeLeft*1000:0"
									format="HH:mm:ss"></u-count-down>
							</view>
							<view @click.stop>
								<u-tag text="联系房东" size="mini" @click="contactLandlord(item)" plain
									borderColor='#f56e3d' color="#f56e3d"></u-tag>
							</view>
						</view>
					</view>
				</view>
				<view class="" style="padding-bottom: 40rpx;">
					<u-loadmore :status="status" />
				</view>
			</view>
		</view>
		<u-toast ref="uToast"></u-toast>
	</view>
</template>

<script>
	import {
		survey
	} from '@/api/survey/index.js'

	export default {
		data() {
			return {
				surveyState: '',
				pageList: [],
				searchParams: {
					pageNum: 1,
					pageSize: 10,
				},
				status: 'loading',
				// 抢单状态 1 待确认 2 勘察中 3 勘察完毕 4 已取消
				surveyStateObj: {
					1: "待确认",
					2: "勘察中",
					3: "勘察完毕",
					4: "已取消",
				},
				longitude: '',
				latitude: ''

			}
		},

		onLoad(options) {
			this.initSearch()
			uni.$on('refresh', () => {
				this.initSearch()
			})
			setTimeout(() => {
				
			}, 350)
			this.insertAppLoaction()
		},
		// onShow() {
		// 	this.insertAppLoaction()
		// },
		onPullDownRefresh() {
			//this.status = 'loading';
			this.initSearch()
			this.$refs.uToast.show({
				type: "success",
				message: '刷新成功',

			})
		},
		onReachBottom(e) {
			this.searchParams.pageNum++
			this.getList()
		},
		computed: {
			leftNum() {
				return this.pageList.filter((item) => ((item.surveyState === 1 || item.surveyState === 2) && item
					.timeLeft >
					0)).length
			}
		},
		methods: {
			initSearch() {
				this.status = 'loading'
				this.searchParams.pageNum = 1
				this.pageList = []
				this.getList()
			},
			getList() {
				if (this.status === 'nomore') return
				survey.myEnsurelask(this.searchParams).then(res => {
					if (res.data.code == 200) {
						this.pageList = this.pageList.concat(res.data.data.records)
						if (this.pageList.length >= res.data.data.total) {
							this.status = 'nomore'
							return
						} else {
							this.status = 'loading'
						};
					}
				});
			},
			gotoGrabbingHall() {
				console.log(this.pageList);
				if (this.pageList.length >= 5) {
					this.$refs.uToast.show({
						message: '先去完成勘察任务后再来吧',
						type: "error"
					})
				} else {
					uni.navigateTo({
						url: '/pages/survey/grabbingHall'
					})
				}


			},
			contactLandlord({
				landlordPhone
			}) {
				uni.makePhoneCall({
					phoneNumber: landlordPhone //仅为示例
				});
			},
			gotoRecord() {
				uni.navigateTo({
					url: '/pages/survey/grabbingRecords/grabbingRecords'
				})
			},
			gotoDetails({
				id: id,
				houseId,
				surveyState
			}) {
				//surveyState 抢单状态 1已抢单 2 可勘察 3 勘察完毕 4 已取消
				switch (surveyState) {
					case 1:
						uni.navigateTo({
							url: '/pages/survey/surveyTask?id=' + id
						})
						break;
					case 2:
						uni.navigateTo({
							url: '/pages/survey/surveySubmit?id=' + id + '&houseId=' + houseId
						})
					default:
						break;
				}

			},

			 insertAppLoaction() {

				uni.getLocation({
					type: 'gcj02',
					geocode: true,
					success: async (obj) => {
						console.log(obj);
						let getState = obj.errMsg;
						if (getState == 'getLocation:ok') {
							this.longitude = obj.longitude;
							this.latitude = obj.latitude;
							let uid = uni.getStorageSync("uid")
							const token = uni.getStorageSync('token');
							const location = {
								"requestPath": 2,
								"longitude": this.longitude,
								"latitude": this.latitude,
								"userId": uid
							}
							
							
							const res = await survey.insertAppLoaction(location)
						}  
					},
					fail(err) {
					 /* if (err.errCode === 3) {
					      wx.showModal({
					        title: '位置检索超时',
					        content: '请检查您的网络连接和定位服务设置，然后重试。',
					        showCancel: false,
					        success(modalRes) {
					          if (modalRes.confirm) {
					            wx.getLocation({
					              type: 'gcj02',
					              geocode: true,
					              success(res) {
									this.longitude = res.longitude;
									this.latitude = res.latitude;
					              },
					              fail(err) {
					                // console.error('重新获取位置失败:', err);
									uni.showToast({
										title:'重新获取位置失败',
										icon:'none'
									})
					              }
					            });
					          }
					        }
					      });
					    } else {
					        uni.showToast({
					        	title:'位置检索失败',
								icon:'none'
					        })
					    } */
						
						//第一次获取失败，第二次再请求
						
						uni.getLocation({
							type: 'gcj02',
							altitude: true,
							success: (obj) => {
								console.log(obj);
								let getState = obj.errMsg;
								if (getState == 'getLocation:ok') {
									this.longitude = obj.longitude;
									this.latitude = obj.latitude;
									let uid = uni.getStorageSync("uid")
									const token = uni.getStorageSync('token');
									const location = {
										"requestPath": 2,
										"longitude": this.longitude,
										"latitude": this.latitude,
										"userId": uid
									}
									
									
									const res =  survey.insertAppLoaction(location)
								} 
							},
							fail(err) {
								uni.showModal({
									title: '重要提示!',
									content: '为了提供更精准位置服务，您需要打开手机的定位功能且赋予App使用位置服务的权限！否则将无法正常使用App功能',
									showCancel: false,
									success: function(res) {
										if (res.confirm) {
											//plus.runtime.quit();
										}
									}
								});
								fUN_AmapLocation.stop({}, result => {
						
								});
							},
						
						});
						
					},
					complete:   () => {
						
 
					}
				});


			}
		},
	}
</script>
<style lang="scss">
	.top_title {
		padding: 20rpx;
		background: linear-gradient(to bottom, #fb7f52, #f1f1fe);

		.title {
			position: relative;

			.record {
				position: absolute;
				right: 20rpx;
				top: 0;
			}
		}

		.new_people {
			display: flex;
			justify-content: space-between;
			align-items: center;
			padding: 0 20rpx;
		}

		.grabbing_hall {
			height: 300rpx;
			display: flex;
			justify-content: center;
			align-items: center;
			background-color: #fff;
			border-radius: 10rpx;

			.hall_home {
				display: flex;
				justify-content: center;
				align-items: center;
				background: #f56e3d;
				border-radius: 60rpx;
				padding: 10rpx 20rpx;
			}
		}
	}

	.mid {
		background-color: #fff;
		padding: 30rpx 20rpx;
		display: flex;
		justify-content: flex-end;
		align-items: center;
		font-size: 12px;
		white-space: nowrap;

		text {
			color: red;
		}
	}

	.blue {
		height: 60rpx;
		background-color: #d2e0ff;
	}

	.bottom {

		.empty {
			display: flex;
			flex-direction: column;
			justify-content: center;
			align-items: center;
			padding: 60rpx 0;
		}
	}

	.page_wrapper {
		background-color: #eee;

		.item {
			padding: 20rpx 40rpx;
			margin-bottom: 20rpx;
			background-color: #fff;

			.top,
			.mid,
			.btm,
			.state {
				display: flex;
				justify-content: space-between;
				align-items: center;
			}

			.top_mid {
				display: flex;
				justify-content: space-between;
				padding: 10rpx 0;

				.map {
					display: flex;
					justify-content: space-between;
				}
			}

			.btm_time {
				display: flex;
				justify-content: space-between;
				align-items: center;

				/deep/ .u-count-down__text {
					color: #eeaf78;
					padding-left: 10rpx;
					font-size: 12px;
				}
			}
		}
	}
</style>